<script lang="ts">
    import { Tooltip } from "../Tooltip";
    import { useClassList } from "../utils/useClassList";
    import { useStyle } from "../utils/useStyle";
    import type { TitleProps } from "./Typography";

    const props: TitleProps = $props();

    const classList = $derived(
        useClassList(props, "cm-typograghy-title", `cm-typograghy-h${props.heading ?? 1}`, {
            "cm-typograghy-title-inline": props.inline,
            [`cm-typograghy-title-prefix-${props.prefix}`]: props.prefix,
            "cm-text-with-ellipsis": !!props.ellipsis,
        })
    );

    const style = $derived(
        useStyle(props, {
            "background-image": props.gradient ? `linear-gradient(${props.gradient.join(",")})` : "",
            "-webkit-text-fill-color": props.gradient ? "transparent" : "",
            [`--cm-title-prefix-width`]: `${props.prefixWidth ?? (props.prefix === "bar" ? 4 : 8)}`,
            [`--cm-title-prefix-gap`]: `${props.prefixGap ?? 16}`,
            [`--cm-title-prefix-color`]: typeof props.prefixColor === "string" ? props.prefixColor : "",
            [`--cm-title-prefix-gradient`]: props.prefixColor instanceof Array ? props.prefixColor.join(",") : "",
        })
    );

    const showTooltip = $derived.by(() => typeof props.ellipsis === "object" && props.ellipsis.showTooltip);
    const tooltipOptions = () => {
        if (showTooltip && typeof (props.ellipsis as any).showTooltip === "object") {
            return (props.ellipsis as any).showTooltip;
        }
        return {
            content: props.children,
        };
    };
</script>

{#snippet title()}
    <svelte:element this={`h${props.heading ?? 1}`} class={classList} {style}>{@render props.children?.()}</svelte:element>
{/snippet}

{#if showTooltip}
    <Tooltip {...tooltipOptions()}>
        {@render title()}
    </Tooltip>
{:else}
    {@render title()}
{/if}
